
const sqlite3 = require("sqlite3").verbose();
const path = require("path");
const { TEMP_PATH } = require("./helper")
// 创建或打开数据库
let dbPath = path.join(TEMP_PATH,"database.sqlite")

const initDatabase = () => {
  global.db = new sqlite3.Database(dbPath, (err) => {
    if (err) {
      console.error("Could not connect to database", err);
    } else {
      console.log("Connected to database");
    }
  });
  // 创建打印日志记录表
  global.db.serialize(() => {
    db.run(`
    CREATE TABLE IF NOT EXISTS print_logs (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      uuid TEXT ,
      createTime DATETIME DEFAULT CURRENT_TIMESTAMP,
      printerName TEXT,
      status TEXT,
      html TEXT,
      width INTEGER,
      height INTEGER,
      templateJson TEXT,
      templateName TEXT,
      printData TEXT,
      pageNum INTEGER,
      errorMessage TEXT,
      printOptions TEXT
    )
  `);
    // 打印日志表索引
    db.run(`
    CREATE INDEX IF NOT EXISTS idx_print_logs_uuid ON print_logs (uuid);
  `);

    db.run(`
    CREATE TABLE IF NOT EXISTS images (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      uuid TEXT,
      createTime DATETIME DEFAULT CURRENT_TIMESTAMP,
      filePath TEXT,
      url TEXT,
      urlMd5 TEXT,
      status TEXT
    )
  `);

    // 零售报告表
    db.run(`
    CREATE TABLE IF NOT EXISTS retail_report (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      uuid TEXT,
      type BLOB,
      jsonData TEXT,
      createTime  DATETIME DEFAULT CURRENT_TIMESTAMP,
      dataIndex INTEGER
);
  `);

    // 添加索引
    db.run(`
    CREATE INDEX IF NOT EXISTS idx_retail_report_uuid_dataIndex ON retail_report (uuid, dataIndex);
  `);

    // 添加新的可选字段 rePrintAble，默认值为 1
    // db.run(
    //   `
    //   ALTER TABLE print_logs ADD COLUMN rePrintAble INTEGER DEFAULT 1;
    //   ALTER TABLE print_logs ADD COLUMN html TEXT;
    // `,
    //   (err) => {
    //     if (err && !err.message.includes("duplicate column")) {
    //       console.error("添加新字段时出错:", err);
    //       log("添加新字段时出错:" + err.message);
    //     }
    //   },
    // );
  });

}

module.exports = {
  initDatabase
};
